# coding=utf-8
from rest_framework.utils import json

from worldcup.apps.userModel.models import UserConfig, User
from worldcup.commons.CommonResult import rest, CommonResult


@rest
def get_config(request):
	openid = request.GET.get("openid")
	if openid is None:
		return CommonResult(-1, "openid不能为空")
	configs = UserConfig.objects.filter(openid=openid).all()
	if len(configs) > 0:
		config = configs[0]
		return CommonResult(0, config.config)
	else:
		return CommonResult(0, "")


@rest
def set_config(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	openid = reqest_params["openid"]
	if openid == "" or openid is None:
		return CommonResult(-1, "openid不能为空")
	new_config = reqest_params["config"]

	# 判断是否有此openid
	usernum = User.objects.filter(openid=openid).count()
	if usernum == 0:
		return CommonResult(-1, "没有此openid")

	configs = UserConfig.objects.filter(openid=openid).all()
	if len(configs) > 0:
		config = configs[0]
		config.config = new_config
		config.save()
	else:
		config = UserConfig(openid=openid, config=new_config)
		config.save()
	return CommonResult(0, "success")
